<?php

namespace addons\shopro\model\commission;

use think\Model;
use addons\shopro\library\commission\Agent as AgentLibrary;
use Exception;
class Agent extends Model
{
    protected $pk = 'user_id';
    // 表名
    protected $name = 'shopro_commission_agent';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'createtime_text',
        'status_text',
    ];
     public function getStatusTextAttr($value, $data) 
    {
        $status_text = '';

        switch ($data['status']) {
            case AgentLibrary::AGENT_STATUS_NORMAL:
                $status_text = '正常';
                break;
            case AgentLibrary::AGENT_STATUS_PENDING:
                $status_text = '审核中';
                break;
            case AgentLibrary::AGENT_STATUS_FREEZE:
                $status_text = '冻结';
                break;
            case AgentLibrary::AGENT_STATUS_FORBIDDEN:
                $status_text = '禁用';
                break;
            case AgentLibrary::AGENT_STATUS_NEEDINFO:
                $status_text = '完善资料';
                break;
            case AgentLibrary::AGENT_STATUS_REJECT:
                $status_text = '审核驳回';
                break;
        }

        return $status_text;
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        return date("Y-m-d H:i:s",$data['createtime']);
    }
    public static function getRanking($params) {
        extract($params);

        $goods = self::with(['user' => function ($query) {
                        $query->field('id,avatar,nickname');
                    }])
                    ->field('user_id,level,parent_agent_id,total_income,createtime,status')
                    ->normal()
                    ->order('total_income', 'desc')->order('createtime', 'desc')
                    ->paginate($per_page ?? 10);

        return $goods;
    }


    /**
     * 正常的分销商
     */
    public function scopeNormal($query) {
        return $query->where('status', AgentLibrary::AGENT_STATUS_NORMAL);
    }
    /**
     * 可参与的分销商
     */
    public function scopeAvaliable($query) {
        return $query->where('status', 'in', [AgentLibrary::AGENT_STATUS_NORMAL, AgentLibrary::AGENT_STATUS_FREEZE]);
    }
    /**
     * 禁用的分销商
     */
    public function scopeForbidden($query) {
        return $query->where('status', AgentLibrary::AGENT_STATUS_FORBIDDEN);
    }
    /**
     * 审核中的分销商
     */
    public function scopePending($query) {
        return $query->where('status', AgentLibrary::AGENT_STATUS_PENDING);
    }

    public function user(){
        return $this->belongsTo(\addons\shopro\model\User::class, 'user_id');
    }


    public function level(){
        return $this->belongsTo(\addons\shopro\model\commission\Level::class, 'level', 'level');
    }

    public function getChildAgentLevelAttr($value, $data){
        if(!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    public function setChildAgentLevelAttr($value, $data){
        return json_encode($value);
    }

    public function getChildAgentLevel_1Attr($value, $data){
        if(!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    public function setChildAgentLevel_1Attr($value, $data){
        return json_encode($value);
    }
    /**
     * 订单支付成功
     *
     * @param [type] $order
     * @param [type] $notify
     * @return void
     */
    public function paymentProcess($order, $notify)
    {
        // file_put_contents("1.txt",json_encode($notify));
        // file_put_contents("2.txt",json_encode($order));
        try{
            $order->pay_status = 1;
            $order->status = AgentLibrary::AGENT_STATUS_PENDING;
            $order->paytime = time();
            $order->transaction_id = $notify['transaction_id'];
            $order->payment_json = $notify['payment_json'];
            $order->pay_type = $notify['pay_type'];
            $order->save();
        } catch (Exception $e) {
            file_put_contents("3.txt",$e->getMessage());
        }
        return $order;
    }
    // 获取下级
    public function getChild($user_id){
        // where("status","normal")->
        $child = [];
        $child_1 = [];
        $child_2 = [];
        $list = self::where("parent_agent_id",$user_id)->where("pay_status",1)->column("user_id");
        if(count($list)){
            $child = array_merge($child,$list);
            $child_1 = array_merge($child_1,$list);
            for($i = 0;$i < count($list);$i++){
                $res = $this->getChild($list[$i]);
                $child = array_merge($child,$res['child']);
                $child_2 = array_merge($child_2,$res['child_1']);
            }
        }
        return ["child"=>$child,'child_1'=>$child_1,"child_2"=>$child_2];
    }
}
